import 'package:async/async.dart';
import 'package:boss/main.dart';
import 'package:boss/models/staff_tip_page_data.dart';
import 'package:boss/ui/widget/calendar/util/date_util.dart';
import 'package:boss/ui/widget/loader/loader_pull_refresh.dart';
import 'package:flustars/flustars.dart' as flustars;
import 'package:flutter/material.dart';

class StaffTipProvider extends ChangeNotifier {
  List<StaffTip> staffTips = [];

  DateTime startTime;

  String get startTimeText {
    return startTime == null ? null : flustars.DateUtil.formatDate(startTime, format: flustars.DateFormats.full);
  }

  DateTime endTime;

  String get endTimeText {
    return endTime == null ? null : flustars.DateUtil.formatDate(endTime, format: flustars.DateFormats.full);
  }

  GlobalKey<LoaderPullRefreshState> loaderPullRefreshKey = GlobalKey<LoaderPullRefreshState>();

  int page = 1;

  StaffTipProvider() {
    startTime = DateUtils.startOfTheDay(DateTime.now());
    endTime = DateUtils.endOfTheDay(DateTime.now());
  }

  setStartTime(List<DateTime> dateTime) async {
    startTime = dateTime[0];
    endTime = dateTime[1];
    notifyListeners();

    dateRangeChangeHandle();
  }

  Future<Result<List<StaffTip>>> queryStaffTipList() async {
    try {
      var response = await api.queryWaiterTipList(
        page: page,
        startTime: startTimeText,
        endTime: endTimeText,
      );
      if (!response.successful()) {
        return Result.error(response.msg);
      }

      staffTips = response.data.items;
      notifyListeners();

      return Result.value(response.data.items);
    } catch (e) {
      return Result.error(e.toString());
    }
  }

  Future<Result<List<StaffTip>>> refreshStaffTipList() async {
    page = 1;
    staffTips = [];
    return queryStaffTipList();
  }

  Future<Result<List<StaffTip>>> loadMoreStaffTipList() async {
    page += 1;
    return queryStaffTipList();
  }

  dateRangeChangeHandle() async {
    if (startTime != null && endTime != null) {
      loaderPullRefreshKey.currentState.refresh();
    }
  }
}
